Describe the "name hiding" issue in C++ and how it might lead to logical errors.
Describe the "name hiding" issue in C++ and how it might lead to logical errors.
18116-Aug-2023
Updated on 17-Aug-2023
Home / DeveloperSection / Forums / Describe the "name hiding" issue in C++ and how it might lead to logical errors.
Describe the "name hiding" issue in C++ and how it might lead to logical errors.
Aryan Kumar
17-Aug-2023Sure. Name hiding is a C++ concept that occurs when a name is declared in a scope that hides a name with the same name in an outer scope. This can happen with variables, functions, classes, and other entities.
Name hiding can lead to logical errors if the programmer is not aware of it. For example, consider the following code:
C++
In this code, the
foo()
function inDerived
hides thefoo()
function inBase
. This means that when we callb.foo()
, we are actually calling thefoo()
function inBase
. However, when we calld.foo()
, we are actually calling thefoo()
function inDerived
.If the programmer is not aware of name hiding, they might think that the
foo()
function inDerived
is overriding thefoo()
function inBase
. However, this is not the case. Thefoo()
function inDerived
is simply hiding thefoo()
function inBase
.This can lead to logical errors if the programmer is not careful. For example, if the programmer expects the
foo()
function inDerived
to call thefoo()
function inBase
, they might be surprised when it does not.To avoid name hiding errors, it is important to be aware of the scope of names. When declaring a name, it is important to make sure that the name does not hide a name with the same name in an outer scope.
Here are some tips for avoiding name hiding errors:
using
directive to bring names into scope. This can be useful if you need to use a name from an outer scope in an inner scope.By following these tips, you can help to avoid name hiding errors in your C++ code.